package merlin.utils;

import javax.activation.*;

import java.io.*;

import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;


public class MailSender{


	/**
	 * Simple mail in text/html encoding.
	 */
	public static void sendMail(String from,String to,String subject,String message){
		try{

			ApplicationResources resource = ApplicationResources.getInstance();

			String mailServer = resource.getProperty("mail.smtp.server");
			String userId	  = resource.getProperty("mail.username");
			String password   = resource.getProperty("mail.password");

			//Set the host smtp address
			Properties props = new Properties();
			props.put("mail.smtp.host", mailServer);
			//props.put("mail.smtp.auth", "true");

			//Authenticator auth = new SMTPAuthenticator(userId,password);
			//Session session = Session.getInstance(props, auth);
			Session session = Session.getInstance(props, null);

			// create a message
			Message msg = new MimeMessage(session);

			// set the from and to address
			InternetAddress addressFrom = new InternetAddress(from);
			msg.setFrom(addressFrom);

			msg.setRecipient(Message.RecipientType.TO,new InternetAddress(to));

			// Setting the Subject and Content Type
			msg.setSubject(subject);

			//msg.setContent(message, "text/html");
			DataHandler msgHandler = new  DataHandler(new ByteArrayDataSource(message, "text/html"));
			msg.setDataHandler(msgHandler);

			// add the sent date
			msg.setSentDate(new Date());

			Transport.send(msg);

		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("Could not send mail to " + to ,e);
		}
	}

	/**
	 * Mail with attachment.
	 */
	public static void sendMail(String from,String to,String subject,String message,String messageMimeType,byte[] attachmentData,String attachmentMimeType,String fileName)throws MessagingException{
		ApplicationResources resource = ApplicationResources.getInstance();

		String mailServer = resource.getProperty("mail.smtp.server");
		String userId	  = resource.getProperty("mail.username");
		String password   = resource.getProperty("mail.password");

		// add handlers for main MIME types
		MailcapCommandMap mc = (MailcapCommandMap)CommandMap.getDefaultCommandMap();
		mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
		mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
		mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
		mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
		mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
		CommandMap.setDefaultCommandMap(mc);


		//Set the host smtp address
		Properties props = new Properties();
		props.put("mail.smtp.host", mailServer);
		//props.put("mail.smtp.auth", "true");

		//Authenticator auth = new SMTPAuthenticator(userId,password);
		//Session session = Session.getInstance(props, auth);
		Session session = Session.getInstance(props, null);

		// create a message
		Message msg = new MimeMessage(session);

		// set the from and to address
		InternetAddress addressFrom = new InternetAddress(from);
		msg.setFrom(addressFrom);

		msg.setRecipient(Message.RecipientType.TO,new InternetAddress(to));

		// Setting the Subject and Content Type
		msg.setSubject(subject);

		//msg.setContent(message, "text/html");
		MimeBodyPart partMessage = new MimeBodyPart();
		DataHandler msgHandler = new  DataHandler(new ByteArrayDataSource(message, messageMimeType));
		partMessage.setDataHandler(msgHandler);

		// set the attachment.
		MimeBodyPart partAttachment = null;
		if(attachmentData != null){
			partAttachment = new MimeBodyPart();
			DataHandler attchHandler = new DataHandler(new ByteArrayDataSource(attachmentData, attachmentMimeType));
			partAttachment.setDataHandler(attchHandler);
			partAttachment.setFileName(fileName);
		}

		// create the Multipart and its parts to it
		Multipart mp = new MimeMultipart();
		mp.addBodyPart(partMessage);
		if(attachmentData != null)mp.addBodyPart(partAttachment);

		// add the Multipart to the message
		msg.setContent(mp);

		// add the sent date
		msg.setSentDate(new Date());

		Transport.send(msg);
	}

	/***
	private static class SMTPAuthenticator extends javax.mail.Authenticator{
		String userId, password;
		SMTPAuthenticator(String userId,String password){
			this.userId = userId;
			this.password = password;
		}
		public PasswordAuthentication getPasswordAuthentication(){
        	return new PasswordAuthentication(userId, password);
    	}
	}
	***/


	static class ByteArrayDataSource implements DataSource {
    	private byte[] data;	// data
	    private String type;	// content-type

		public ByteArrayDataSource(String data, String type) {
			try {
				this.data = data.getBytes("iso-8859-1");
			}catch(UnsupportedEncodingException uex){
				uex.printStackTrace();
			}
			this.type = type;
		}

		public ByteArrayDataSource(byte[] data, String type) {
			this.data = data;
			this.type = type;
		}

		public InputStream getInputStream() throws IOException {
			if (data == null)
	    		throw new IOException("no data");
			return new ByteArrayInputStream(data);
    	}

    	public OutputStream getOutputStream() throws IOException {
			throw new UnsupportedOperationException("Cannot create output stream");
    	}

    	public String getContentType() {
        	return type;
    	}

    	public String getName() {
        	return "dummy";
    	}
	}
}